// customController project customController.go
package controllers

import (
	"3rd/errors"
	goerrors "github.com/go-errors/errors"
	"github.com/revel/revel"
	"io/ioutil"
	"time"
	"dataPublisher/app/models"
)

type Controller struct {
	*revel.Controller
	t    time.Time
	body []byte
}

func (c *Controller) RenderResult(obj interface{}) revel.Result {
	switch obj.(type) {
	case *errors.CustomError:
		ce := obj.(*errors.CustomError)
		// TODO: remove
		if c.Request.Locale == "" {
			c.Request.Locale = models.ZH_CN
		}
		ce.Msg = models.ErrMap[c.Request.Locale][ce.ErrCode] + " " + ce.Error()
		models.Log.Error(ce.ErrorStack())
		return c.RenderJson(*ce)
	case *goerrors.Error:
		ce := obj.(*goerrors.Error)
		models.Log.Error(obj.(*goerrors.Error).ErrorStack())
		return c.RenderJson(errors.CustomError{Msg: ce.Error()})
	case error:
		ce := obj.(error)
		models.Log.Error("%v", obj)
		return c.RenderJson(errors.CustomError{Msg: ce.Error()})
	default:
		return c.RenderJson(errors.CustomError{Msg: errors.SUCC, Data: obj})
	}
}

func (c *Controller) StartAction() revel.Result {
	defer c.Request.Body.Close()
	var err error
	c.body, err = ioutil.ReadAll(c.Request.Body)
	if err != nil {
		revel.ERROR.Println(err)
		return nil
	}
	c.t = time.Now()
	models.Log.Debug("Begin request %s: %s from:%s",
		c.Request.RequestURI, c.body, c.Request.RemoteAddr)
	return nil
}

func (c *Controller) EndAction() revel.Result {
	models.Log.Debug("End response %s: %+v used:%v",
		c.Request.RequestURI, c.Result, time.Since(c.t))
	return nil
}

func init() {
	revel.InterceptMethod((*Controller).StartAction, revel.BEFORE)
	revel.InterceptMethod((*Controller).EndAction, revel.AFTER)
}
